﻿$(function () {
    var curFuncId = 0;  //自定义函数ID

    var editor = CodeMirror.fromTextArea(document.getElementById("expression"), {
        lineNumbers: true,  // 显示行号
        matchBrackets: true,
        styleActiveLine: true,
        extraKeys: { "Ctrl-Space": "autocomplete" },
        modex: "css/javascript/htmlmixed",
        indentUnit: 4,
        smartIndent: true,  // 是否智能缩进
    });

    //自定义函数实体映射
    var FormFunc = function () {
        this.ID = curFuncId;
        this.FuncName = $("#txtFuncName").val();
        this.FuncCaption = $("#txtFuncCaption").val();
        //this.FuncType = $("#selType").val();
        this.FuncType = $("#selFuncType").val();
        this.Description = $("#desc").val();
        this.Expression = editor.getValue();
    };

    //函数分类基本比较固定，目前在这里写死了
    var FuncTypeMapper = new Object();
    FuncTypeMapper["系统函数"] = "系统函数";
    FuncTypeMapper["功能函数"] = "功能函数";
    FuncTypeMapper["计算函数"] = "计算函数";

    function BindFuncTypeToControls() {
        var innerStr = "";
        for (var f in FuncTypeMapper) {
            innerStr += "<option value='" + f.toString() + "'>" + FuncTypeMapper[f] + "</option>"
        }
        $(".funcTypeMapper").html(innerStr);
    };

    var InitTable = function () {
        //模板列表
        $("#formFuncTable").bootstrapTable({
            height: 380,
            method: "post",
            url: "../../FormDesign/QueryByFuncType",
            cache: false,
            queryParamsType: "limit",
            toolbar: "#toolbar",
            toolbarAlign: 'left',
            //search: true,
            //trimOnSearch: true,
            striped: false,
            clickToSelect: true,
            singleSelect: true,
            idField: "ID",
            uniqueId: "ID",

            smartDisplay: true,
            responseHandler: function (ret) {
                return ret.Data
            },
            contentType: 'application/json',
            dataType: "json",
            columns: [
                { titleTooltip: "全选/全不选", checkbox: true, align: 'center', valign: 'middle' },
                { field: "FuncName", title: "函数名", align: 'center', valign: 'middle' },
                { field: "FuncCaption", title: "函数功能", align: 'center', valign: 'middle' }
            ],
            queryParams: function (params) {
                if ($("#selType").val() == null) {
                    return false;
                } else {
                    params.FuncType = $("#selType").val();
                    return params;
                }
            },
            onLoadSuccess: function (data) {
                InitButton();
                InitForm();
                return false;
            },
            onLoadError: function (status) {
                return false;
            },
            onCheck: function(){
                InitButton();
                InitForm();
            },
            onUncheck: function () {
                InitButton();
                InitForm();
            },
        });
    };

    //函数分类改变事件
    $("#selType").change(function () {
        $("#formFuncTable").bootstrapTable('refresh');
    });
    var InitForm = function () {
        var formFunc = new FormFunc();
        var selectRow = $("#formFuncTable").bootstrapTable('getSelections');
        if (selectRow.length != 0) {
            curFuncId = selectRow[0].ID;
            $("#txtFuncName").val(selectRow[0].FuncName);
            $("#txtFuncCaption").val(selectRow[0].FuncCaption);
            $("#selFuncType").val(selectRow[0].FuncType);
            $("#desc").val(selectRow[0].Description);
            editor.setValue(selectRow[0].Expression);
        } else {
            formFunc.ID = 0;
            $("#txtFuncName").val("");
            $("#txtFuncCaption").val("");
            $("#selFuncType").val("");
            $("#desc").val("");
            editor.setValue("");
        }
    }

    var InitButton = function () {
        var selectRow = $("#formFuncTable").bootstrapTable('getSelections');
        if (selectRow.length == 1) {
            $("#update").removeClass("disabled");
            $("#delete").removeClass("disabled");
            $("#txtFuncName")[0].disabled = true;
        } else {
            $("#update").addClass("disabled");
            $("#delete").addClass("disabled");
            $("#txtFuncName")[0].disabled = false;
        }
    };

    var InitPage = function () {
        BindFuncTypeToControls();
        InitTable();
        InitButton();
        InitForm();
    };

    var ValidSyntax = function () {
        var funcstr = editor.getValue();
        try {
            eval(funcstr);
            alert("函数语法验证成功！");
        } catch (e) {
            alert("函数语法验证失败！错误信息：" + e.Message);
        }
        //alert("暂未实现");
    };

    //检测函数
    var CheckFunc = function () {
        var funcstr = editor.getValue();
        var startPos = funcstr.indexOf("function") + 8;
        var endPos = funcstr.indexOf("(");
        var funName = funcstr.substring(startPos, endPos);

        if ($.trim(funName) != $("#txtFuncName").val()) {
            alert("不能保存，函数体中的名称和预定义的函数名称不一致！");
            return false;
        }
        return true;
    };

    //新增自定义函数
    $("#create").click(function () {
        var formFunc = new FormFunc();
        if (CheckFunc()) {
            $.ajax({
                type: "POST",
                url: "../../FormDesign/AddFormFunc",
                data: { JsonStr: JSON.stringify(formFunc) },
                success: function (msg) {
                    if (msg.Result) {
                        alert("添加成功。");
                        $("#formFuncTable").bootstrapTable('refresh');
                        InitForm();
                    } else {
                        alert("添加失败" + msg.Message);
                    }
                },
                error: function (r, s, e) {
                    alert("出错：" + e);
                }
            });
        }
    });

    //修改自定义函数
    $("#update").click(function () {
        var selectRow = $("#formFuncTable").bootstrapTable('getSelections');
        curFuncId = selectRow[0].ID;
        var formFunc = new FormFunc();
        if (CheckFunc()) {
            $.ajax({
                type: "POST",
                url: "../../FormDesign/UpdateFormFunc",
                data: { JsonStr: JSON.stringify(formFunc) },
                success: function (msg) {
                    if (msg.Result) {
                        alert("修改成功。");

                        $("#formFuncTable").bootstrapTable('refresh');
                        InitForm();
                    } else {
                        alert("修改失败" + msg.Message);
                    }
                },
                error: function (r, s, e) {
                    alert("出错：" + e);
                }
            });
        }
    });

    //删除事件
    $("#delete").click(function () {
        var selectRow = $("#formFuncTable").bootstrapTable('getSelections');
        curFuncId = selectRow[0].ID;
        var formFunc = new FormFunc();
        var ret = confirm("您确定要删除函数名为 【 " + formFunc.FuncName + " 】的函数吗 ?");
        if (ret) {
            $.ajax({
                type: "POST",
                url: "../../FormDesign/DeleteFormFunc",
                data: { JsonStr: JSON.stringify(formFunc) },
                success: function (msg) {
                    if (msg.Result) {
                        alert("删除成功。");

                        $("#formFuncTable").bootstrapTable('refresh');
                        InitForm();
                    } else {
                        alert("删除失败" + msg.Message);
                    }
                },
                error: function (r, s, e) {
                    alert("出错：" + e);
                }
            });
        }
    });

    //清空
    $("#clear").click(function(){
        $("#txtFuncName").val('');
        $("#txtFuncCaption").val('');
        $("#desc").val('');
        editor.setValue('');
    });

    //检测按钮事件
    $("#validBtn").on("click", ValidSyntax);

    //初始化页面信息
    InitPage();
});

